# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
import urllib

_APIKEY = '05dbdf63020c6b5811939e2906254208'
MovieSearchUrl = 'http://api.douban.com/movie/subjects?%s'

class DoubanAPI:
    def searchMovie(self, q, tag = '', max_results = 1, start_index = 1):
        print 'search movie...'
        ids = []
        params = urllib.urlencode({'q':q.encode('utf-8'),\
                                    'tag': tag,\
                                    'max-results':max_results,\
                                    'start-index':start_index,\
                                    'apikey':_APIKEY})
        ret = urllib.urlopen(MovieSearchUrl%params).read()
#        print >> open('in.txt','w'), ret
        soup = BeautifulSoup(ret)
        for entry in soup('entry'):
            ids.append(entry.id.contents[0].rsplit('/',1)[1])
        if ids == []:
            return None
        return tuple(ids)
    
    def findMovieByID(self, id):
        print 'search id...'
        _url = 'http://api.douban.com/movie/subject/'+id
        print 'movie url:',
        print _url
        ret = urllib.urlopen(_url).read()
        soup = BeautifulSoup(ret)
#        print >> open('in.txt','w'), soup.prettify()
        title = soup.title.contents[0]
        content = soup.summary.contents[0]
        rating = soup.find('gd:rating')
        average_rating = rating['average']
        numraters = rating['numraters']
        i = ('title', 'content', 'averageRating','raters')
        q = (title, content, average_rating, numraters)
        return dict(zip(i,q))
    
    def findCommentByID(self, id, max_results = 3):
        print 'search comment...'
        _url = 'http://api.douban.com/movie/subject/%s/reviews?max-results=%s' %(id, max_results)
        print 'comment url:',
        print _url
        ret = urllib.urlopen(_url).read()
        soup = BeautifulSoup(ret)
        qq = tuple([(entry.title.contents[0], entry.summary.contents[0]) for entry in soup('entry')])
        return qq
#        print >> open('in.txt', 'w'), soup.prettify()
        
if __name__ == '__main__':
    dou = DoubanAPI()
    print dou.searchMovie(u'卡耐可视对讲')
    
    